<template>
  <el-drawer
    ref="drawerBox"
    v-bind="$attrs"
    :wrapper-closable="true"
    :close-on-press-escape="false"
    :visible.sync="drawerShow"
    :size="showMobilePage ? '100%' : '80%'"
    title="引用发票信息"
    append-to-body
  >
    <div class="drawer-content">
      <filter-input
        v-if="!isOther"
        ref="FilterToolRef"
        v-model="filterInput"
        :filter-list="filterList"
        show-search-btn
        line-feed
        @handelClick="queryClick"
        @queryEmpty="queryEmpty"
      />
      <template v-else>
        <div class="flex-center field-list">
          <div v-for="item in otherFilterList" :key="item.keyword" :label="item.name" class="flex-center field-item">
            <span class="label">{{ item.name }}</span>
            <el-input
              v-model="otherFilterInput[item.keyword]"
              :placeholder="item.placeholder || '请输入内容'"
              :type="item.inputType || 'text'"
              :maxlength="item.lengthLimit ? (item.maxLength || 100) : null"
              style="width: 160px;"
              size="small"
              clearable/>
          </div>
          <el-button :disabled="searchOtherDisabled" type="primary" style="width: 40px; height: 32px; padding: 0" @click="queryClick">
            <img :src="searchIcon" width="16px" height="16px" alt="" style="filter: brightness(999);">
          </el-button>
          <div class="operate-btn" @click="queryEmpty">
            <el-tooltip :open-delay="500" content="重置筛选" placement="top">
              <img :src="resetFilterIcon" class="operate-icon" alt="">
            </el-tooltip>
          </div>
        </div>
      </template>
      <el-tabs v-if="multiple" v-model="curTabName" type="card" class="tab-content" @tab-click="onSubActiveOrderChange">
        <el-tab-pane label="可见发票" name="all"/>
        <el-tab-pane label="不可见发票" name="other"/>
      </el-tabs>
      <div :style="multiple?'':{marginTop: '17px'}" class="table-list">
        <div v-loading="listLoading">
          <el-table
            v-if="(curTabName === 'all' && list.items.length > 0) || (curTabName === 'other' && otherList.items.length > 0)"
            ref="legalTableRef"
            :data="curTabName === 'all' ? list.items : otherList.items"
            :row-class-name="(data) => tableRowClassName(data)"
            :height="setTableHeight"
            class="fb-table"
            header-cell-class-name="order-data-header-cell"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            fit
            select-callback
            hightlight-current-rowref="tableRef"
            @select="selectTable"
            @select-all="selectTable">
            <el-table-column
              fixed="left"
              align="center"
              type="selection"
              width="50"
            />
            <el-table-column align="left" label="发票类型" min-width="80">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.invoiceType | inputInvoiceType" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="发票项目" min-width="100">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.invoiceProject" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="发票代码" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.invoiceCode" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="发票号码" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.invoiceNo" class="link" @click.native="toDetail(scope.row)"/>
              </template>
            </el-table-column>
            <el-table-column align="left" label="开票日期" min-width="120" prop="invoiceDate">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.invoiceDate, 'YYYY/MM/DD')" />
              </template>
            </el-table-column>
            <el-table-column align="right" label="含税金额(元)" min-width="130" prop="invoicePrice">
              <template slot-scope="scope">
                <PriceColumn :real-val="scope.row.invoicePrice" :price="scope.row.invoicePrice" />
              </template>
            </el-table-column>
            <el-table-column align="right" label="不含税金额(元)" min-width="130" prop="invoicePrice">
              <template slot-scope="scope">
                <PriceColumn :real-val="scope.row.money" :price="scope.row.money" />
              </template>
            </el-table-column>
            <el-table-column align="right" label="税额(元)" min-width="130" prop="invoicePrice">
              <template slot-scope="scope">
                <PriceColumn :real-val="scope.row.taxAmount" :price="scope.row.taxAmount" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="发票状态" min-width="80">
              <template slot-scope="scope">
                <StatusText
                  v-if="scope.row.invoiceStatus || scope.row.invoiceStatus===0"
                  :color="['#FFBC3D','#406EFF', '#31CC9C', '#999', '#31CC9C','#406EFF'][scope.row.invoiceStatus]"
                  :text="scope.row.invoiceStatus | inputInvoiceStatus"
                />
                <div v-else>--</div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="票据附件" min-width="180">
              <template slot-scope="scope">
                <FileShowList v-if="showAttachment(scope.row)" :file-list="getAttachmentUrl(scope.row.attachmentUrlStr)" style="max-width:100%;" is-show-single-file />
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column align="left" label="创建人">
              <template slot-scope="scope">
                <CheckUserInfo v-if="scope.row.creator" :label="scope.row.creator" :user-id="scope.row.creatorId" />
                <div v-else>--</div>
              </template>
            </el-table-column>
            <el-table-column min-width="180" align="left" label="创建时间">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.createTime, 'YYYY/MM/DD HH:mm')" />
              </template>
            </el-table-column>
          </el-table>
          <empty-placeholder v-else :empty-img="emptyImg" :text="isOther ? '同时精准搜索发票代码+发票号码+含税金额，即可查找无权限查看的发票' : ''" :empty-text-top="8" :text-color="'#999'" image-size="140px" bold-text="找不到发票，请换个关键词搜索"/>
        </div>
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <el-pagination
            v-show="(curTabName === 'all' && list.items.length> 0) || (curTabName === 'other' && otherList.items.length> 0)"
            :current-page="curTabName === 'all'?list.page:otherList.page"
            :page-size="curTabName === 'all'?list.perPage:otherList.perPage"
            :total="curTabName === 'all'?list.total:otherList.total"
            :small="true"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="showMobilePage?'total, prev, next,jumper':'total, prev, pager, next, sizes,jumper'"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <fixed-pagination class="bottom-pagination">
          <div class="delete-button-container">
            <el-button :disabled="multiple && !hasSelected" size="small" type="primary" class="related-btn" @click="quoteInvoice">确认</el-button>
            <el-button size="small" plain type="primary" class="related-btn" @click="onBackClick">返回</el-button>
          </div>
          <el-pagination
            v-show="(curTabName === 'all' && list.items.length> 0) || (curTabName === 'other' && otherList.items.length> 0)"
            :current-page="curTabName === 'all'?list.page:otherList.page"
            :page-size="curTabName === 'all'?list.perPage:otherList.perPage"
            :total="curTabName === 'all'?list.total:otherList.total"
            :small="true"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="showMobilePage?'total, prev, next,jumper':'total, prev, pager, next, sizes,jumper'"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </fixed-pagination>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import FilterInput from '@/components/Tool/filter';
import FileShowList from '@/components/CreateOrder/fileShowList';
import { getInputInvoiceList } from '@/api/inputInvoice';
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import options from '@/views/legal/module/options';
import { format } from '@/filters/date';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { inputInvoiceStatus, inputInvoiceType } from '@/filters/status';
import { invoiceTypeOption } from '@/views/inputInvoice/options';
import { mapState } from 'vuex';
import resetFilterIcon from '@/assets/setting/resetFilter.png';
import emptyImg from '@/assets/empty-search.png';
import searchIcon from '@/assets/search-resource.png';

export default {
  name: 'RelatedContract',
  filters: {
    inputInvoiceType,
    inputInvoiceStatus
  },
  components: {
    FilterInput,
    EmptyPlaceholder,
    FileShowList
  },
  mixins: [tableSelections, TableAdaptive],
  props: {
    multiple: {
      type: Boolean,
      default: true
    },
    excludeCancel: {
      type: Boolean,
      default: false
    },
    hasContractCode: {
      type: Boolean,
      default: false
    },
    confirmText: {
      type: String,
      default: '确认'
    }
  },
  data() {
    return {
      searchIcon,
      emptyImg,
      resetFilterIcon,
      filterInput: {},
      otherFilterInput: {},
      drawerShow: false,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0
      },
      sortType: '',
      sortName: '',
      listLoading: false,
      options,
      idKey: 'id', // 多选框参数
      tableRefName: 'legalTableRef',
      curTabName: 'all',
      selectedData: [],
      otherList: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0
      },
      statusOption: [{ value: 0, label: '执行中' },
        { value: 1, label: '待认证' },
        { value: 2, label: '认证中' },
        { value: 3, label: '已完成' }]
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    hasSelected() {
      return this.multipleSelectionAll.length > 0;
    },
    isOther() {
      return this.curTabName === 'other';
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 280 : 223;
    },
    otherFilterList() {
      return [
        { keyword: 'invoiceCode', name: '发票代码', labelWidth: '100px' },
        { keyword: 'invoiceNo', name: '发票号码', labelWidth: '100px' },
        { keyword: 'invoicePrice', name: '含税金额', labelWidth: '100px' }
      ];
    },
    searchOtherDisabled() {
      const { invoiceNo, invoiceCode, invoicePrice } = this.otherFilterInput;
      return !invoiceNo || !invoiceCode || !invoicePrice;
    },
    filterList() {
      return [
        // 输入框
        { keyword: 'invoiceProject', name: '发票项目', labelWidth: '100px', type: 'input' },
        { keyword: 'invoiceNo', name: '发票号码', labelWidth: '100px', type: 'input' },
        { keyword: 'invoiceCode', name: '发票代码', labelWidth: '100px', type: 'input' },
        // 范围
        { keyword: 'invoicePrice', name: '含税金额', labelWidth: '100px', type: 'inputRange',
          isRequired: true, startPlaceholder: '最低金额', endPlaceholder: '最高金额', max: 999999999 },
        // 下拉
        { keyword: 'invoiceType', name: '发票类型', type: 'select', options: invoiceTypeOption },
        { keyword: 'certificateStatus', name: '发票状态', type: 'select', options: this.statusOption },
        // 时间
        { keyword: 'invoiceDate', name: '开票日期', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' }
      ];
    },
    rangeKeyArr() {
      return [
        { attr: 'invoiceDate', start: 'invoiceDateStart', end: 'invoiceDateEnd', type: 'time', addTime: true },
        { attr: 'invoicePrice', start: 'invoicePriceStart', end: 'invoicePriceEnd', type: 'number' }
      ];
    }
  },
  watch: {
    list: {
      handler: function(data) {
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(data.items);
        });
      },
      deep: true
    }
  },
  methods: {
    format,
    // 初始获取数据
    openDialog() {
      this.fetchData(true);
      this.curTabName = 'all';
      this.drawerShow = true;
    },
    // fitter
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.filterInput = {};
      this.clearOtherData();
      if (this.isOther && JSON.stringify(this.otherFilterInput) === '{}') return;
      this.queryClick();
    },
    handleSizeChange(val) {
      this.isOther ? (this.otherList.perPage = val) : (this.list.perPage = val);
      this.fetchData(true);
    },
    handleCurrentChange(toPage) {
      this.isOther ? (this.otherList.page = toPage) : (this.list.page = toPage);
      this.fetchData();
    },
    toDetail(row) {
      const url = this.$router.resolve({
        name: 'inputInvoiceDetail',
        query: { id: row.id }
      });
      window.open(url.href, '_blank');
    },
    // 获取列表数据
    fetchData(reset = false) {
      try {
        if (reset) this.isOther ? (this.otherList.page = 1) : (this.list.page = 1);
        this.listLoading = true;
        const params = _.cloneDeep(this.isOther ? this.otherFilterInput : this.filterInput);
        !this.isOther && paramsRangeFormat(this.rangeKeyArr, params);
        params.page = this.isOther ? this.otherList.page : this.list.page;
        params.perPage = this.isOther ? this.otherList.perPage : this.list.perPage;
        params.isOther = this.isOther ? 1 : 0;
        getInputInvoiceList(params).then(({ data }) => {
          this.isOther ? (this.otherList = data) : (this.list = data);
          this.listLoading = false;
        }, result => {
          this.listLoading = false;
        }).catch(e => {
          console.error(e);
        });
      } catch (error) {
        console.log(error);
      }
    },
    showAttachment(row) {
      const attachmentUrl = this.getAttachmentUrl(row.attachmentUrlStr);
      if (!attachmentUrl || attachmentUrl.length === 0) {
        return false;
      } else {
        const urlList = attachmentUrl.map(item => item.url);
        return !urlList.includes(null);
      }
    },
    getAttachmentUrl(attachmentUrlStr) {
      return attachmentUrlStr ? JSON.parse(attachmentUrlStr) : '';
    },
    // 切换列表tab
    onSubActiveOrderChange(data) {
      if (!this.isOther) {
        this.fetchData();
      } else {
        if (this.setSelectRow) this.setSelectRow(this.otherList.items);
      }
    },
    quoteInvoice() {
      this.$emit('quoteInvoice', this.multipleSelectionAll);
      this.onBackClick();
    },
    clearOtherData() {
      this.otherFilterInput = {};
      this.otherList = {
        items: [],
        page: 1,
        perPage: 20,
        total: 0
      };
    },
    onBackClick() {
      this.$refs.drawerBox.closeDrawer();
      this.multipleSelectionAll = [];
    }
  }
};
</script>

<style scoped lang="scss">
.field-list {
  .field-item {
    margin-right: 48px;
  }
  .field-item:nth-child(3) {
    margin-right: 16px;
  }
}

.link {
  color: #406eff;
  cursor: pointer;
}
.filter-input-search {
  @include flexStyle(center, center);
  border-radius: 4px;
  border: none;
  padding: 0;
  width: 40px;
  height: 32px;
  background: #406eff;
  cursor: pointer;
  .el-icon-search {
    font-size:16px;
    color: #fff;
  }
}
.operate-btn {
  width: 24px;
  height: 24px;
  cursor: pointer;
  margin-left: 5px;
  @include flexStyle(center, center);
  &.active {
    background-color: #EDEEF2;
    border-radius: 4px;
  }
  .operate-icon {
    width: 16px;
    height: 16px;
  }
}
::v-deep .el-drawer__header {
  height: 48px;
  padding: 0 12px 0 24px;
  margin: 0;
  box-shadow: 2px 4px 5px 0 rgba(221,225,234,0.3);
  display: flex;
  align-items: center;
  > span {
    font-size: 14px;
    color: #333;
  }
  ::v-deep .el-tabs__nav-wrap::after {
    height: 0 !important;
  }
}
::v-deep .el-tabs__header {
  margin: 0;
  border: none;
}
::v-deep .el-drawer__body {
  overflow-y: auto;
  margin-bottom: 56px;
}
::v-deep .el-drawer__header>span{
  font-size: 16px;
}
.drawer-content {
  padding: 22px 24px 0;
  overflow-y: auto;
  .label {
    font-size: 14px;
    color: #666;
    margin-right: 12px;
  }
  .table-list {
    border-radius: 10px;
    .el-row {
      padding: 0;
    }
    .delete-button-container {
      flex:1;
      height: 32px;
      display: flex;
      align-items: center;
      .related-btn {
        margin-left: 20px;
        padding-left: 12px;
        padding-right: 12px;
      }
    }
    &::v-deep {
      .pagination-flex {
        position: absolute;
        width: 100% !important;
      }
      .el-table__header th {
        height: 49px !important;
      }
    }
  }
  .tab-content {
    margin: 17px 0 8px;
    &::v-deep {
      .el-tabs__header  {
        margin-bottom: 0 !important;
        border-bottom: 1px solid #ddd;
        .el-tabs__nav {
          border: none !important;
        }
        .el-tabs__item {
          padding: 0 12px !important;
          height: 32px !important;
          line-height: 32px !important;
          margin-right: 8px;
          border: 1px solid #ddd;
          border-radius: 4px 4px 0px 0px;
          color: #333;
          background: #f7f8fa;
          font-size: 16px;
          &:last-child {
            margin-right: 0px;
          }
          &.is-active {
            border-bottom-color: #FFFFFF !important;
            font-weight: bold;
            background: #fff;
            color: #406eff;
          }
        }
      }
      .el-badge__content{
        background: #FB5227;
        transform: translateY(5px);
      }
    }
  }
}
::v-deep .el-tabs__nav-wrap::after {
  z-index: -1;
}
::v-deep .el-tabs__active-bar {
  bottom: 1px;
}
</style>
